import { Base64 } from '@vimi/utils-tool'
import { BASE_URL } from '@/common/plugins/constant'

export function getScreenSize() {
  const width = document.documentElement.offsetWidth || document.body.offsetWidth || 1920
  const height = document.documentElement.offsetHeight || document.body.offsetHeight || 1080
  return { width, height }
}

export function winOpen({
  url,
  windowName = '_blank',
  windowFeatures: { top = 100, left, width = 900, height, center = true, ...restFeatures } = {},
}) {
  if (center) {
    const { width: sw, height: sh } = getScreenSize()

    if (!height) {
      height = sh - top
    }

    if (!left) {
      left = ~~((sw - width) / 2)
    }
  }

  const features = []
  for (const key in restFeatures) {
    features.push(`${key}=${restFeatures[key]}`)
  }
  const featureStr = features.length ? `,${features.join(',')}` : ''

  return window.open(
    url,
    windowName,
    `width=${width},height=${height},top=${top},left=${left}${featureStr}`
  )
}

export function officePreview({ url, windowName, windowFeatures }) {
  const previewUrl = BASE_URL + '/view'
  const urlBase64 = encodeURIComponent(Base64.encode(url))
  return winOpen({
    url: `${previewUrl}/onlinePreview?url=${urlBase64}`,
    windowName,
    windowFeatures,
  })
}
